<?php


namespace App\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Models\WechatMember;
use App\Models\MemberOther;
use App\Services\CommonService;
use Illuminate\Http\Request;

class AuthorizationController extends Controller
{
    protected $openId;
    protected $appid;
	protected $sessionKey;


    /**
     * 手机号授权
     */
    public function grantAuthPhone(Request $request){
        $input = $request->input();

        if(!isset($input['openId'])||empty($input['openId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请登录后授权手机号码');
        }

        $code=isset($input['code'])?$input['code']:'';
        if($code){
            $appid=config('wechat.appId');
            $secret=config('wechat.appSecret');
            $openid=$input['openId'];

             //手机号码
            $access_arr = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
            $access_arr = json_decode($access_arr,true);
            $access_token = $access_arr['access_token'];
            $phone_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
            $postdata =json_encode(["code"=>$code]);

            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-type:application/x-www-form-urlencoded',
                    'content' => $postdata,
                    'timeout' => 15*60*10 // 超时时间（单位:s）
                )
            );
            $context = stream_context_create($options);
            $result = file_get_contents($phone_url, false, $context);
            $result = json_decode($result,true);

            // dd($result);
            $mobile = $result['phone_info']['phoneNumber'];

                $memberData['mobile']=$mobile;

            $uid = MemberOther::where('mobile',$mobile)->value('id');

            if($uid && $uid>0){
                $memberData['other_user_id'] = $uid;
            }else{
                $memberData['other_user_id'] = 0;
            }

            $is_member = WechatMember::where(['openId'=>$openid])->first();
            $is_member = obToArray($is_member);

            if($is_member){
                WechatMember::where(['openId'=>$openid])->update($memberData);
            }else{
                $memberData['create_time'] = date('Y-m-d H:i:s');
                WechatMember::where(['openId'=>$openid])->insert($memberData);
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'手机号授权成功',$memberData);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'手机号未授权');
        }


    }

    /**
     * 用户授权
     */
    public function grantAuth(Request $request){
        $input = $request->input();
        $appid=config('wechat.appId');
        $secret=config('wechat.appSecret');
        $code = $input['code'];
        $url_open = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $date_open = file_get_contents($url_open);
        $date_open = json_decode($date_open,true);
        // dd($date_open);

        $this->openId = $date_open['openid'];
        $this->sessionKey = $date_open['session_key'];
		$this->appid = $appid;

        //添加更新数据
        $memberData['head_image'] = isset($input['userInfo']['avatarUrl']) ? $input['userInfo']['avatarUrl'] : ''; //头像
        $memberData['nick_name'] = isset($input['userInfo']['nickName']) ? $input['userInfo']['nickName'] : ''; //昵称

        $memberData['city'] = isset($input['userInfo']['city']) ? $input['userInfo']['city'] : '';  //城市
        $memberData['country'] = isset($input['userInfo']['country']) ? $input['userInfo']['country'] : ''; //国家
        $memberData['province'] = isset($input['userInfo']['province']) ? $input['userInfo']['province'] : ''; //省份
        $gender = isset($input['userInfo']['gender']) ? $input['userInfo']['gender'] : ''; //性别
        $memberData['gender'] =$gender==1?'女':'男' ;


        //返回数据
        $data['avatarUrl'] = $memberData['head_image'];
        $data['nickName'] = $memberData['nick_name'];

        $memberData['openId'] = $this->openId;
        $memberData['session_key'] = $this->sessionKey;
        $memberData['token'] = createToken($this->openId);
        $memberData['update_time'] = date('Y-m-d H:i:s');
        $memberData['status'] = CommonService::SHOP_ENABLE; //启用

        $is_member = WechatMember::where(['openId'=>$this->openId])->first();
        $is_member = obToArray($is_member);

        if($is_member){
            WechatMember::where(['openId'=>$this->openId])->update($memberData);
        }else{
            $memberData['contract_no'] = isset($input['clickId']) ? $input['clickId'] : '';  //城市
            if(isset($input['account'])&&$input['account']){
                $memberData['from'] = isset($input['account']) ? $input['account'] : '';  //城市
            }
            $memberData['create_time'] = date('Y-m-d H:i:s');
            WechatMember::where(['openId'=>$this->openId])->insert($memberData);
        }
        $data['openId'] = $this->openId;
        $data['token'] = $memberData['token'];


        $url = 'http://tracking.e.qq.com/conv';
        if($memberData['contract_no']){
            $param = [
                'actions'=>[
                    [
                        "action_time"=>time(),
                        "user_id"=>['wechat_openid'=> $data['openId'],'wechat_app_id'=>config('wechat.appId')],
                        "action_type"=>"REGISTER",
                        "trace"=>['click_id'=>$memberData['contract_no']],
                        "action_param"=>['value'=>'0'],
                    ]
                ],
            ];
            $result = http_post($url,json_encode($param),['Content-type: application/json;charset=UTF-8']);
            $result=json_decode($result,true);
            $content = [
                'request'=>is_object($param) ? object_array($param) : $param,
                'response'=>is_object($result) ? object_array($result) : $result,
            ];
            \Illuminate\Support\Facades\Log::debug('注册转化归因',$content);
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'授权成功',$data);

    }




}
